package br.com.galante.webapp.view;

import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

@Named("usuario")
@RequestScoped
public class UsuarioView implements Serializable {

	private static final long serialVersionUID = 3003388582729162781L;
	
    
	public String logout(){
		// Get the existing session. 
//		FacesContext context = (FacesContext) FacesContext.getCurrentInstance();  
//	    HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
		// Invalidate the existing session. 
//		if(FacesContext.getCurrentInstance().getExternalContext().
//			       getUserPrincipal() != null) { 
//			session.invalidate();
//		} 
//		return "/home.jsf";
		String result = "/home.jsf";
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.
                getExternalContext().getRequest();
        try {
            System.out.println("calling logout");
            request.logout();
            System.out.println("called logout");
        } catch (ServletException ex) {
            Logger.getLogger(UsuarioView.class.getName()).
                    log(Level.SEVERE, null, ex);
            result = "/public/erro.jsf";
        }
        return result;
	}
	public boolean isSigned() {
		return (getUserName() != null);
	}
	
	public String getUserName(){
		FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.
                getExternalContext().getRequest();
		return request.getRemoteUser();
	}
//	public boolean isSigned() {
//		return (FacesContext.getCurrentInstance().getExternalContext()
//				.getSession(false) != null && FacesContext.getCurrentInstance()
//				.getExternalContext().getUserPrincipal() != null);
//	}
//	
//	public String getUserName(){
//		return FacesContext.getCurrentInstance().getExternalContext().
//	       getUserPrincipal().getName();
//	}
}
